/*
 * @Author: 赵宇
 * @Description:
 * @Date: 2023-04-18 16:55:23
 * @LastEditTime: 2023-04-18 17:15:41
 * @LastEditors: zhao 13370229059@163.com
 * @FilePath: \pcj\src\config\upload.js
 */
// An highlighted block
import { get, post } from '@/api/index';
export default async function upload(file, limit = 5, folder = 0, callback) {
  if (!file) return;
  let val = {};
  // 没有限制的时候最大只能5m
  if (file.size / 1024 > limit * 1024) {
    ElMessage({
      message: `文件过大！不能超过${Number(limit)}M ！`,
      type: 'warning'
    });
    return;
  }
  // 初始化实例
  let data = {
    Token:
      'fhOyI4T8IbI2GovVDMRdxtiTVXWO89Aa60f495e146cbc5b4508c2bf6ab491d6adKAqO3J709xZyCKWcoeLa5DXBjtw-YrLSo3xU2k6W1U7c5RmHRtOK7uwQFCrAXHA0p_ejEwSBFk80z_dRoL7eoJ-D9eDFadUnD79MO_tewxapc2cODx5_MYBdi8fVQbyAKPzEtD-SG9cK4vf0QzShPnLv5k3463f5UQaaQi28tH7Qisf2sYXjFMfqlQ9AOL1Wksk0rs1nUpbroE5rxOZCaeT5lgMo_BOrSBZl-pCQovopRZtbkLsCofRuRL25fkWtqIOz2JsEv0tBibOAhseMb2UkmihJgk4Bkk5NvMOTb_fQmdCBruZZoXTaA0naeCqfCE_NZeBxe-bgR1X4kSu_TVSaTHB2ktn96xunkrrR6poiOrSI58ZnODT9fsDfwIuJvv0euq3FwMSdI0CUL1pBH7dmPxX4v62Ym3lGNBJ8wzHkAbTyln1TuW5HruCRfsb5ZGhWtOz9Ad_siyWkEE_m3kyFwLGWoGzE5_HkQXPTPBKFm_fOEtYotGfLfgmMSHjF6jq8Dg4StzkLS9GaKtENrE2LSZnP8VGWq4Lpb09_LmNy8qbzWplXfO5UcVqnePgeMo6OxpO7eLp2FYUPWac3S0AVwwElCbQ-px4TnWS7LfwgVAzf4zvYIyBJTXUVya5PlfRvRf1jvUsr71Q4jy-I9oo2CRyu77gqILFY2vPlWJ612RsvKQsTXpP2Twlo_AQoOoeq1pWGoR2jD5TFgdIGS8X0URHlJXwGBceZn94_drARsXtItIlS92lrEGL1TjZC8f_D-0He35jWfonHCcr2bg7cX7iS-vrKLFEiblObvH_Mp_ZjSnDl1uTn31ir4zphrnNAytTKOAOuhQb0nUHA4pN8_0eIzK5tDjZv_xF3nc0fV310W92jpLQ11FIdspBpm9Bz8-01uKMB3ARSvdHfw',
    TmpSecretId: 'AKIDW-aSgL3f47kXYzYWNWtnqd1NCqRCYWQOIGpuzShJ2h5VAO8Ein8gA8I4OCWYzt8b',
    TmpSecretKey: 'iRR05DPZYcQF6srtu7wDYugTDXJJPFxud0uXcchXR5I=',
    error: null,
    expiredTime: 1681815424,
    region: 'ap-shanghai',
    bucket: 'yewuwang',
    cdn: 'https://cdn.yewuwang.net',
    appId: '1256137602'
  };
  // data = JSON.parse(localStorage.getItem('uploadData'));
  // if (!data || !data.expiredTime || !moment().isBefore(moment(data.expiredTime * 1000))) {
  //   data = await get('TencentCos/Sts').then(data => data.result);
  // }
  // data = { ...data, ...data.credentials };
  // delete data.credentials;
  // localStorage.setItem('uploadData', JSON.stringify(data));
  let cos = new COS({
    getAuthorization: function (options, callback) {
      callback({
        TmpSecretId: data.TmpSecretId,
        TmpSecretKey: data.TmpSecretKey,
        XCosSecurityToken: data.Token,
        ExpiredTime: data.expiredTime
      });
      val = { ...options };
    }
  });
  return new Promise(function (resolve, reject) {
    let type = false;
    let name = file.name.substring(file.name.lastIndexOf('.') + 1, file.name.length);
    let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
    if (['jpg', 'png', 'img', 'jpeg', 'JPG', 'PNG', 'IMG', 'JPEG'].includes(name)) {
      type = true;
    }
    let obj = {
      Bucket: data.bucket + '-' + data.appId /* 必须 */,
      Region: data.region /* 存储桶所在地域，必须字段 */,
      Key: `/${['UploadFile', 'Import'][folder]}/${moment().format(
        'YYYY/MM/DD'
      )}/${guid()}.${name}` /* 必须  这是对象键 me.jpg || 20200813/me.jpg 支持这些格式 具体看文档 https://cloud.tencent.com/document/product/436/13324 */,
      StorageClass: 'STANDARD',
      Body: file, // 上传文件对象
      ContentType: file.type,
      ContentDisposition: `${type ? 'inline' : 'attachment'}; filename=${window.encodeURI(file.name)}`,
      /* inline attachment 图片是预览，文件是下载,fileename 必须要用encodeURI包裹，不然中文文件名无法识别 */
      onProgress: val => {
        if (callback) {
          callback(val);
        }
      }
    };
    cos.putObject(obj, (err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve({
          ...res,
          ...val,
          ...{ url: data.cdn + val.Pathname, name: file.name, isImg: type, fileType: fileType, uid: file.uid, size: file.size }
        });
      }
    });
  });
}

function guid() {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
}
